{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow.examples.tutorials.mnist import input_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-2-4d2900e3cbe3>:2: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From D:\\Anaconda\\empty\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From D:\\Anaconda\\empty\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting MNIST_data/train-images-idx3-ubyte.gz\n",
      "WARNING:tensorflow:From D:\\Anaconda\\empty\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting MNIST_data/train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From D:\\Anaconda\\empty\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Extracting MNIST_data/t10k-images-idx3-ubyte.gz\n",
      "Extracting MNIST_data/t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From D:\\Anaconda\\empty\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From D:\\Anaconda\\empty\\lib\\site-packages\\tensorflow\\python\\framework\\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Colocations handled automatically by placer.\n",
      "WARNING:tensorflow:From <ipython-input-2-4d2900e3cbe3>:27: BasicLSTMCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.LSTMCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-2-4d2900e3cbe3>:30: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From <ipython-input-2-4d2900e3cbe3>:36: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "\n",
      "Future major versions of TensorFlow will allow gradients to flow\n",
      "into the labels input on backprop by default.\n",
      "\n",
      "See `tf.nn.softmax_cross_entropy_with_logits_v2`.\n",
      "\n",
      "Iter0,Testing Accuracy=0.7304\n",
      "Iter1,Testing Accuracy=0.8471\n",
      "Iter2,Testing Accuracy=0.8826\n",
      "Iter3,Testing Accuracy=0.9057\n",
      "Iter4,Testing Accuracy=0.9212\n",
      "Iter5,Testing Accuracy=0.9208\n"
     ]
    }
   ],
   "source": [
    "#载入数据集\n",
    "mnist = input_data.read_data_sets(\"MNIST_data/\",one_hot=True)\n",
    "\n",
    "#输入图片是28*28\n",
    "n_inputs = 28#输入一行的长度 取决于图片一行28像素\n",
    "max_time = 28#一共28行\n",
    "lstm_size = 100#100个隐层单元\n",
    "n_classes = 10#10个分类\n",
    "batch_size = 50#每批次50样本\n",
    "n_batch = mnist.train.num_examples // batch_size#计算一共多少批次 \n",
    "\n",
    "#这里的none表示第一个维度可以任意，取决于放多少张图片\n",
    "x = tf.placeholder(tf.float32,[None,784])\n",
    "#正确的标签\n",
    "y = tf.placeholder(tf.float32,[None,10])\n",
    "\n",
    "#初始化权值\n",
    "weights = tf.Variable(tf.truncated_normal([lstm_size,n_classes],stddev=0.1))\n",
    "#初始化偏置值\n",
    "biases = tf.Variable(tf.constant(0.1,shape=[n_classes]))\n",
    "\n",
    "#定义RNN网络\n",
    "def RNN(X,Weights,Biases):\n",
    "    #inputs = [batch_size,max_time,n_inputs]\n",
    "    inputs = tf.reshape(X,[-1,max_time,n_inputs])\n",
    "    #定义LSTM基本CELL\n",
    "    lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(lstm_size)\n",
    "    #final_state[0]是cell state\n",
    "    #final_state[1]是hidden_state\n",
    "    outputs,final_state = tf.nn.dynamic_rnn(lstm_cell,inputs,dtype=tf.float32)\n",
    "    results = tf.nn.softmax(tf.matmul(final_state[1],Weights)+Biases)\n",
    "    return results\n",
    "#计算RNN的返回结果\n",
    "prediction = RNN(x,weights,biases)\n",
    "#损失函数\n",
    "cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y))\n",
    "#使用AdamOptimizer进行优化\n",
    "train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n",
    "#把结果存放在一个布尔型列表中\n",
    "correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))\n",
    "#求准确率\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n",
    "#初始化\n",
    "init = tf.global_variables_initializer()\n",
    "\n",
    "with tf.Session() as sess:\n",
    "    sess.run(init)\n",
    "    for epoch in range(6):\n",
    "        for batch in range(n_batch):\n",
    "            batch_xs,batch_ys = mnist.train.next_batch(batch_size)\n",
    "            sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})\n",
    "            \n",
    "        acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})\n",
    "        print(\"Iter\" + str(epoch) + \",Testing Accuracy=\" + str(acc))\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
